package emi99

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"github.com/go-pay/gopay"
	"strings"
)

func (c *Client) Sha256WithRsa(privateRaw string, bm gopay.BodyMap) (string, error) {
	//私钥
	privateRaw = strings.Trim(privateRaw, "\n")
	if !strings.HasPrefix(privateRaw, "-----BEGIN RSA PRIVATE KEY-----") {
		privateRaw = fmt.Sprintf("%s\n%s\n%s", "-----BEGIN RSA PRIVATE KEY-----", privateRaw, "-----END RSA PRIVATE KEY-----")
	}
	blockPri, _ := pem.Decode([]byte(privateRaw))
	if blockPri == nil {
		return "", fmt.Errorf("blockPri is nil")
	}
	rsaPri, e := genPriKey(blockPri.Bytes)
	if e != nil {
		panic(e)
	}

	//数据加密
	signParams := bm.EncodeAliPaySignParams()
	//signStr := fmt.Sprintf("charset=UTF-8&data=%s&nonceStr=%s&partnerNo=%s&signType=%s",
	//	data, "fcdf7badb1f64e1490ec22cdc21b6c3a", c.partnerNo, "RSA")
	h := sha256.New()
	h.Write([]byte(signParams))
	d := h.Sum(nil)
	signature, err := rsa.SignPKCS1v15(rand.Reader, rsaPri, crypto.SHA256, d)
	if err != nil {
		return "", err
	}
	encodedSig := base64.StdEncoding.EncodeToString(signature)

	return encodedSig, nil
}
func genPriKey(privateKey []byte) (*rsa.PrivateKey, error) {
	var priKey *rsa.PrivateKey
	prkI, err := x509.ParsePKCS8PrivateKey([]byte(privateKey))
	if err != nil {
		return nil, err
	}
	priKey = prkI.(*rsa.PrivateKey)
	return priKey, nil
}
